require 'rubygems'
require 'fsdb'
require File.dirname(__FILE__) + '/const'

class Installr::Database::Storage
  def initialize(log, options={})
    @options = options.dup
    @log = log
    @db_dir = File.expand_path(@options[:data_base_dir] + '/' + Installr::Database::STORAGE_BASENAME)
    puts @db_dir if @options[:verbose]
  end

  def browse_dir(path)
    @db.browse path do |entries|
      entries.each do |entry|
        yield entry
      end
    end
  end

  def browse_each_child(path)
    @db.browse_dir path do |child_path|
      @db.browse child_path do |child_object|
        yield child_path, child_object
      end
    end
  end

  def open
    @db = FSDB::Database.new(@db_dir)
    rescue FSDB::Database::CreateFileError
      puts "[storage:open] cannot create database #{db_dir}"
      @log.error("[storage:open] cannot create database #{db_dir}")
      exit(false)
  end

    def create_deployment(app_name, time_stamp, war_file, md5hash, local_upload_path)
    unless @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+md5hash]
      @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+md5hash] = [time_stamp, war_file, md5hash, local_upload_path]
      @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+'0'] = [time_stamp, war_file, md5hash, local_upload_path]
      return 0
    else
      return -1
    end
  end

  def delete_deployment(app_name)
    return -1 unless @db[Installr::Database::DEPLOY_PATH+'/'+app_name]
    elements = []
    @db[Installr::Database::DEPLOY_PATH+'/'+app_name].each do |element|
      elements << element
    end
    elements.each do |element|
      @db.delete(Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+element)
    end
    @db.delete(Installr::Database::DEPLOY_PATH+'/'+app_name)
    return 0
  end

  def change_deployment(app_name, md5hash)
    if @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+md5hash]
      target_obj = @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+md5hash]
      @db.delete(Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+'0')
      @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+'0'] = target_obj
      return 0
    else
      return -1
    end
  end

  def info_deployment(app_name, md5hash)
    if @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+md5hash]
      obj = @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+md5hash]
      return [obj[0], obj[1], obj[2], obj[3]]
    else
      return nil
    end
  end

  def history_deployment(app_name)
    elements = []
    histories = []
    if @db[Installr::Database::DEPLOY_PATH+'/'+app_name]
      @db[Installr::Database::DEPLOY_PATH+'/'+app_name].each do
        |element|
          elements << element
      end
      elements.each do
        |element|
          history = @db[Installr::Database::DEPLOY_PATH+'/'+app_name+'/'+element]
          histories << history if element != '0'
      end
    end
    histories
  end
end
